/**
 * 添加角色 编辑角色
 * @author xiaoxujs
 */

import { FC, useCallback, useEffect, useRef, useState } from "react";
import { DrawerAddChangeBox, FormBox, FormItemBox, FormItemBoxHeight } from "./style";
import InputX from "../../../../../components/InputX";
import Tree from '../../../../../components/Tree'
import { ISyhtMenuGetMenuAllTree } from "../../../../../type/ConfigManagement/MenuPage/api";
import { postSyhtMenuGetMenuAllTree } from "../../../../../api/ConfigManagement/menuPageApi";
import { TreeFZProps } from "../../../../../type/common";
import ButtonX from "../../../../../components/ButtonX";
import { postSyhtRoleAddRole, getSyhtRoleGetRole, postSyhtRoleUpdateRole } from "../../../../../api/ConfigManagement/rolePageApi";
import { ISyhtRoleGetRole } from "../../../../../type/ConfigManagement/RolePage/api";

export const DrawerAddChange: FC<{
    open: boolean, // 是否打开
    onClose: () => void, // 关闭抽屉
    roleId?: string, // 角色ID 编辑角色时使用
}> = ({
    open, // 是否打开
    onClose, // 关闭抽屉
    roleId
}) => {
        const DrawerBoxRef = useRef<HTMLDivElement>(null);
        const DrawerBoxContentRef = useRef<HTMLDivElement>(null);
        const [roleName, setRoleName] = useState<string>(''); // 角色名称
        const [roleLabel, setRoleLabel] = useState<string>(''); // 角色标签
        const [treeData, setTreeData] = useState<TreeFZProps[]>([]); // 树状结构数据
        const [selectIdArr, setSelectIdArr] = useState<string[]>([]); // 选中的id数组
        const treeFun = useCallback(
            async () => {
                const { code, msg, data } = await postSyhtMenuGetMenuAllTree() as { code: number, msg: string, data: ISyhtMenuGetMenuAllTree[] };
                if (code === 200) {
                    let list: TreeFZProps[] = []
                    // 遍历树形结构， 复制一个新的树形结构
                    const loop = (data: ISyhtMenuGetMenuAllTree[], arr: TreeFZProps[]) => {
                        data.forEach((item) => {
                            let tepData: TreeFZProps = {
                                title: item.menuName,
                                key: item.menuId,
                                menuType: item.menuType, // 菜单类型 0 目录 1 菜单 2 按钮
                            }
                            if (item.children && item.children.length > 0) {
                                tepData.children = [];
                                loop(item.children, tepData.children)
                            }
                            arr.push(tepData)
                        })
                    }
                    loop(data, list);
                    setTreeData(list);
                } else {
                    alert(msg)
                }
            },
            [],
        )
        useEffect(() => {
            console.log(roleId)
           ;(async () => {
            if(roleId) {
                const { code, msg, data } = await getSyhtRoleGetRole({ roleId }) as { code: number, msg: string, data: ISyhtRoleGetRole };
                if (code === 200) {
                    setRoleName(data.roleName); // 角色名称
                    setRoleLabel(data.roleLabel); // 角色标签
                    setSelectIdArr(data.menuIdRoleList); // 选中的id数组 
                }else{
                    alert(msg)
                }
            }
           })(); 
        }, [roleId])

        useEffect(() => {
            treeFun();
        }, [treeFun])

        // 点击取消按钮
        const handleCancel = useCallback(
            () => {
                setRoleName(''); // 角色名称
                setRoleLabel(''); // 角色标签
                setSelectIdArr([]); // 选中的id数组

            },
            [],
        )

        useEffect(() => {

            if (DrawerBoxRef.current && DrawerBoxContentRef.current) {

                DrawerBoxRef.current.addEventListener('click', (event: any) => {
                    if (DrawerBoxContentRef.current?.contains(event.target as Node)) {

                    } else {
                        handleCancel();
                        onClose();
                    }
                })
            }
        }, [handleCancel, onClose]);

        //  修改角色名称
        const handleChangeRoleName = (value: string) => {
            setRoleName(value);
        }
        // 修改权限标识
        const handleChangeRoleLabel = (value: string) => {
            setRoleLabel(value);
        }
        // 点击确定按钮
        const handleSumber = async () => {
            if (roleName === '') {
                alert('角色名称不能为空')
                return; 
            }else if (roleLabel === '') {
                alert('权限标识不能为空')
                return;
            }else if (selectIdArr.length === 0) {
                alert('请选择权限')
                return;

            }else{
                if(roleId) {
                    const params = {
                        roleId, // 角色ID
                        roleName, // 角色名称
                        roleLabel, // 权限标识
                        menuIdList: selectIdArr, // 菜单id列表
                    }
                    console.log(params)
                    const { code, msg } = await postSyhtRoleUpdateRole(params) as { code: number, msg: string };
                    if (code === 200) {
                        alert('修改成功')
                        handleCancel();
                        onClose(); 
                    }else{
                        alert(msg)
                    }
                }else{
                    const params = {
                        roleName, // 角色名称
                        roleLabel, // 权限标识
                        menuIdList: selectIdArr, // 菜单id列表
                    }
                    console.log(params)
                    const { code, msg } = await postSyhtRoleAddRole(params) as { code: number, msg: string };
                    if (code === 200) {
                        alert('添加成功')
                        handleCancel();
                        onClose(); 
                    }else{
                        alert(msg)
                    }
                }
               
            }
        }

        return <DrawerAddChangeBox ref={DrawerBoxRef} open={open}>
            <div ref={DrawerBoxContentRef} className="drawer_content" >
                <div className="drawer_header">
                    <div className="drawer_title">添加</div>
                    <span className="guanbi" aria-hidden="true" onClick={() => {
                        handleCancel()
                        onClose();
                    }}>&times;</span>
                </div>
                <div className="drawer_body">
                    <FormBox>
                        <FormItemBox>
                            <div className="form_title_box">角色名称</div>
                            <InputX value={roleName} onChange={handleChangeRoleName} />
                        </FormItemBox>
                        <FormItemBox>
                            <div className="form_title_box">权限标识</div>
                            <InputX value={roleLabel} onChange={handleChangeRoleLabel} />
                        </FormItemBox>
                        <FormItemBoxHeight>
                            <div className="form_title_box">分配权限</div>
                            <div className="tree_box">
                                <Tree treeData={treeData} selectIdArr = {selectIdArr} setSelectIdArr = {setSelectIdArr}  />
                            </div>
                        </FormItemBoxHeight>

                    </FormBox>
                </div>
                <div className="drawer_footer">
                    <div style={{ marginRight: '2rem' }}>
                        <ButtonX type="info" onClick={() => {
                            handleCancel()
                            onClose();
                        }}>取消</ButtonX>
                    </div>
                    <ButtonX type='primary' onClick={() => handleSumber()}>确定</ButtonX>
                </div>
            </div>
        </DrawerAddChangeBox>
    }

export default DrawerAddChange;

